<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>数字化面粉车间监测系统</title>
    <script type="text/javascript" src="js/jquery.js"></script>
    <link rel="stylesheet" href="css/style.css">
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        .head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
        }

        .pulll_left {
            float: left;
        }

        .menu2 ul {
            list-style: none;
            padding: 0;
            margin: 0;
            display: flex;
        }

        .menu2 ul li {
            margin-right: 20px;
        }

        .menu2 ul li a {
            color: white;
            text-decoration: none;
        }

        .time {
            float: right;
        }

        .mainbox {
            padding: 20px;
        }

        .nav1 {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .box {
            padding: 20px;
            border-radius: 8px;
        }

        .tit {
            font-size: 24px;
            margin-bottom: 20px;
        }

        .boxnav {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
        }

        .yqlist ul {
            display: flex;
            justify-content: space-around;
            width: 100%;
            padding: 0;
        }

        .yqlist li {
            list-style: none;
            text-align: center;
            margin-bottom: 10px;
        }

        .yqlist .yq {
            font-size: 18px;
            margin: 40px;
            margin-bottom: 5px;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .yqlist .yq img {
            width: 50px;
            height: 50px;
        }

        .yqlist .yq span {
            margin-top: 5px;
        }

        .toggle-button {
            width: 80px;
            height: 30px;
            border-radius: 15px;
            background-color: rgb(199, 199, 199);
            position: relative;
            cursor: pointer;
            margin-top: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
            font-weight: bold;
        }

        .toggle-button::after {
            content: '';
            width: 28px;
            height: 28px;
            background-color: white;
            border-radius: 50%;
            position: absolute;
            top: 1px;
            left: 1px;
            transition: left 0.3s;
        }

        .toggle-button.on {
            background-color: rgb(62, 82, 213);
        }

        .toggle-button.on::after {
            left: 51px;
        }

        div.mainbox>div>ul>li>div>div {
            display: flex;

            justify-content: space-between;
            align-items: flex-end;
        }

        div.mainbox>div>ul>li>div {
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        div.mainbox>div>ul>li>div>span {
            color: black;
        }

        .clearfix>li {
            width: 33%;
        }

        .switch-ul {
            display: grid;
            grid-template-columns: repeat(3, 30%);
            grid-template-rows: repeat(3, 30%);
            grid-column-gap: 40px;
            grid-row-gap: 40px;
        }

        .switch-ul>li {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0px 0px 39px -20px skyblue;
            height: 170px;
            transition: all 0.3s linear;
            transform: translateY(0);
        }
        .switch-ul>li:hover {
            transform: translateY(-3px);
            box-shadow: 0px 0px 18px 1px skyblue;
        }
    </style>
</head>

<body>
    <div class="head clearfix">
        <h1 class="pulll_left">数字化面粉车间监测系统</h1>
        <div class="menu menu2 pulll_left">
            <ul>
                <li><a href="./index.html">数据采集</a></li>
                <li><a href="./control.html">设备控制</a></li>
            </ul>
        </div>
        <div class="time" id="showTime">2024/6/11 15:00:12</div>
    </div>

    <div class="mainbox">
        <div class="box" style="width: 1000px;
        margin: 0 auto;">
            <ul class="switch-ul">
                <li>
                    <div class="item" id="jiashi">
                        <span>加湿器</span>
                        <div>
                            <img src="images/jiashi_off.png" alt="Humidifier">
                            <div class="toggle-button" data-device="jiashi">OFF</div>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item" id="shengwen">
                        <span>加热片</span>
                        <div>
                            <img src="images/shengwen_off.png" alt="Heater">
                            <div class="toggle-button" data-device="shengwen">OFF</div>
                        </div>
                    </div>
                </li>

                <li>
                    <div class="item" id="jiangwen">
                        <span>风机</span>
                        <div>
                            <img src="images/jiangwen_off.png" alt="Fan">
                            <div class="toggle-button" data-device="jiangwen">OFF</div>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item" id="fan">
                        <span>通风扇</span>
                        <div>
                            <img src="images/fan_off.png" alt="Fan">
                            <div class="toggle-button" data-device="fan">OFF</div>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item" id="led">
                        <span>灯</span>
                        <div>
                            <img src="images/led_off.png" alt="Light">
                            <div class="toggle-button" data-device="led">OFF</div>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item" id="valve">
                        <span>阀门</span>
                        <div>
                            <img src="images/valve_off.png" alt="Valve">
                            <div class="toggle-button" data-device="valve">OFF</div>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item" id="alarm">
                        <span>报警器</span>
                        <div>
                            <img src="images/alarm_off.png" alt="Alarm">
                            <div class="toggle-button" data-device="alarm">OFF</div>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </div>
    <script>
        var t = null;
        t = setTimeout(time, 1000); //開始运行
        function time() {
            clearTimeout(t); //清除定时器
            dt = new Date();
            var y = dt.getFullYear();
            var mt = dt.getMonth() + 1;
            var day = dt.getDate();
            var h = dt.getHours(); //获取时
            var m = dt.getMinutes(); //获取分
            var s = dt.getSeconds(); //获取秒
            document.getElementById("showTime").innerHTML = y + "/" + mt + "/" + day + " " + h + ":" + m + ":" + s + "";
            t = setTimeout(time, 1000); //设定定时器，循环运行     
        }

        $(document).ready(function () {
            // 页面加载后立即获取并更新数据
            updateData();

            function updateData() {
                var xhr = new XMLHttpRequest(); // 创建对象
                var url = ""; // 替换为实际的服务器端点

                xhr.open("POST", url, true); // 配置请求
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置请求头

                xhr.onreadystatechange = function () { // 检测状态是否发生变化
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var req = xhr.responseText.split(" "); // 响应正文

                        // 在这里处理req数据
                        const devices = ['jiashi', 'shengwen', 'jiangwen', 'fan', 'led', 'valve', 'alarm'];
                        devices.forEach(function (deviceName, i) {
                            const deviceElement = document.querySelector(`[data-device="${deviceName}"]`);
                            if (deviceElement) {
                                const item = req[i];
                                console.log(item);
                                const isOn = item === "1"; // 假设服务器返回的是 "1" 表示开启，"0" 表示关闭
                                const device = document.getElementById(deviceName);
                                const img = device.querySelector('img');
                                const statusText = device.querySelector('span');
                                deviceElement.classList.toggle('on', isOn);
                                deviceElement.textContent = isOn ? 'ON' : 'OFF';
                                img.src = isOn ? `images/${deviceName}_on.gif` : `images/${deviceName}_off.png`;
                                statusText.textContent = statusText.textContent.replace('（开）', '') + (isOn ? '（开）' : '');
                            }
                        });
                    } else if (xhr.readyState === 4) {
                        console.error("请求失败，状态码：" + xhr.status);
                    }
                }

                xhr.send("control"); // 向网页服务器发送请求
            }
        });
        document.addEventListener('DOMContentLoaded', function () {
            // 设备切换状态事件
            document.querySelectorAll('.toggle-button').forEach(button => {
                button.addEventListener('click', function () {
                    const isOn = this.classList.toggle('on');
                    const deviceId = this.getAttribute('data-device');
                    const device = document.getElementById(deviceId);
                    const img = device.querySelector('img');
                    const statusText = device.querySelector('span');

                    // 更新图片和文本
                    img.src = isOn ? `images/${deviceId}_on.gif` : `images/${deviceId}_off.png`;
                    statusText.textContent = statusText.textContent.replace('（开）', '') + (isOn ? '（开）' : '');
                    this.textContent = isOn ? 'ON' : 'OFF';

                    // 更新 JSON 数据
                    updateJsonData(deviceId, isOn ? 1 : 0);
                });
            });

            // 更新 JSON 数据函数
            // 更新服务器数据函数
            function updateJsonData(deviceId, status) {
                var xhr = new XMLHttpRequest();
                var url = "";  // 替换成您的服务器端点
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-Type", "application/json");
                var requestData = `type=10key=${getKeyValue(deviceId)}value=${status}`;
                if (getKeyValue(deviceId) > 300) {
                    requestData = `type=20key=${getKeyValue(deviceId)}value=${status}`;
                }
                // 发送请求
                xhr.send(JSON.stringify(requestData));

                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            console.log("Request sent successfully");
                        } else {
                            console.error("Failed to send request");
                        }
                    }
                };
            }

            // 辅助函数：根据设备 ID 获取对应的 key 值
            function getKeyValue(deviceId) {
                switch (deviceId) {
                    case 'jiashi':
                        return 303;
                    case 'shengwen':
                        return 304;
                    case 'jiangwen':
                        return 305;
                    case 'fan':
                        return 104;
                    case 'led':
                        return 105;
                    case 'valve':
                        return 106;
                    case 'alarm':
                        return 107;
                    default:
                        return -1; // 错误情况处理，需要根据实际情况修改
                }
            }
        });
    </script>
</body>

</html>